package service.impl;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import pojo.FtpUtil;
import pojo.IDUtils;
import service.PictureService;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jordan裔
 * @create 2018-02-10 20:18
 **/
@Service
public class PictureServiceImpl implements PictureService {
    //ftp ip地址
    @Value("${FTP_HOST}")
    private String ftp_host;

    //ftp端口号
    @Value("${FTP_PORT}")
    private int ftp_port;

    //ftp用户名
    @Value("${FTP_USRNAME}")
    private String ftp_username;

    //ftp用户密码
    @Value("${FTP_PASSWORD}")
    private String ftp_password;

    //基础文件目录
    @Value("${FTP_BASEPATH}")
    private String ftp_basepath;

    //文件服务器访问url
    @Value("${IMAGE_URL}")
    private String image_url;

    /**
     * 上传图片
     *
     * @param multipartFile
     * @return
     */
    @Override
    public Map<String, Object> upLoadPicture(MultipartFile multipartFile) {
        try {
        //文件原始名
        String  originalFileName= multipartFile.getOriginalFilename();
        //生成不重复文件新名
        String newFileName = IDUtils.genImageName()+originalFileName.substring(originalFileName.lastIndexOf("."));
        //ftp服务器文件路径
        String imagePath = new DateTime().toString("/yyyy/MM/dd");
        //上传图片
        boolean upLoadImageResult = FtpUtil.uploadFile(ftp_host,ftp_port,ftp_username,ftp_password,ftp_basepath,imagePath,newFileName,multipartFile.getInputStream());
        //文件上传失败处理
        if(!upLoadImageResult){
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("error",1);
            resultMap.put("message","文件上传失败！");
            return resultMap;
        }
            //文件上传成功处理
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("error",0);
            resultMap.put("message",image_url+"/"+newFileName);
            return resultMap;
        } catch (IOException e) {
            //文件上传异常处理
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("error",1);
            resultMap.put("message","文件上传发生异常！");
            return resultMap;
        }
    }
}
